package com.baihui.taobao.transition;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.naming.NamingException;

import org.apache.log4j.Logger;

import com.baihui.taobao.authorize.TaoBaoSessionInfo;
import com.baihui.taobao.db.CommonDAO;
import com.baihui.taobao.db.DBConnectionMgr;
import com.baihui.taobao.db.ItemDao;
import com.baihui.taobao.db.OrderDAO;
import com.baihui.taobao.util.Util;
import com.baihui.taobao.vo.BOrder;
import com.baihui.taobao.vo.BSku;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoObject;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.ItemCat;
import com.taobao.api.domain.Sku;
import com.taobao.api.request.ItemcatsGetRequest;
import com.taobao.api.request.ItemsInventoryGetRequest;
import com.taobao.api.request.ItemsListGetRequest;
import com.taobao.api.request.ItemsOnsaleGetRequest;
import com.taobao.api.response.ItemcatsGetResponse;
import com.taobao.api.response.ItemsInventoryGetResponse;
import com.taobao.api.response.ItemsListGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;

/**
 * @author dev
 *
 */
public class ImportProductDataCase extends Cases implements IViewProgressSupport {

	private ItemDao itemDao=new ItemDao();
	static Logger logger = Logger.getLogger(ImportProductDataCase.class);
	public ImportProductDataCase(TaoBaoSessionInfo info) {
		super(info);
	}

	public void importItemFromTaobao() throws Exception{
		// 获取当前会话用户出售中的商品列表
		long stars = System.currentTimeMillis();
		ItemsOnsaleGetRequest  req=new ItemsOnsaleGetRequest ();
		long page = 1;
		req.setPageSize(200L);
	    req.setPageNo(page);
	    req.setFields("num_iid,title,desc,nick,volume,num,desc,cid,seller_cids,price,score,created,modified,list_time,outer_id");

	    ItemsOnsaleGetResponse  response = getTaoBaoClient().execute(req,getSessionInfo().getTopSession());
	    if(response.getErrorCode() != null){
	    	throw new Exception();
	    }
		List itemList=response.getItems();
        if(itemList==null) return;
        while (response != null && response.getTotalResults() > itemList.size()) {
            page++;
            response = getNextPage(req, page);
            if (response.getErrorCode() == null) {
            	itemList.addAll(response.getItems());
            }else{
                response = getNextPage(req, page);
            	itemList.addAll(response.getItems());
            }
        }
		
        // 得到当前会话用户库存中的商品列表 
        ItemsInventoryGetRequest inventoryreq = new ItemsInventoryGetRequest ();
		long inventoryPage = 1;
		inventoryreq.setPageSize(200L);
		inventoryreq.setPageNo(inventoryPage);
		inventoryreq.setFields("num_iid,title,desc,nick,volume,num,desc,cid,seller_cids,price,score,created,modified,list_time,outer_id ");

	    ItemsInventoryGetResponse inventoryResponse = getTaoBaoClient().execute(inventoryreq,getSessionInfo().getTopSession());
	    if(inventoryResponse.getErrorCode() != null){
	    	throw new Exception();
	    }
	    if(inventoryResponse.getItems() != null){
	    	itemList.addAll(inventoryResponse.getItems());
	    	while (inventoryResponse != null && inventoryResponse.getTotalResults() > itemList.size()) {
	    		inventoryPage++;
	    		inventoryResponse = getInventoryPage(inventoryreq, inventoryPage);
	    		if (inventoryResponse != null) {
	    			itemList.addAll(inventoryResponse.getItems());
	    		}
	    	}
	    }
        
		SKUCase skuCase=new SKUCase(getSessionInfo());
		Iterator itemIterator=itemList.iterator();
		long end = System.currentTimeMillis();
		logger.info("用户[" + getSessionInfo().getVisitor_id() + "]从淘宝上取出" + itemList.size() + "件商品用时" + (end-stars) + "毫秒");
		long nIndex=0;
		Map values = null;
		int insertCount = 0;
		List<Object[]> allInsertTitem = new ArrayList<Object[]>();
		List<Object[]> allUpdateTitem = new ArrayList<Object[]>();
		StringBuffer numIidsBuffer = new StringBuffer();
		int count = 0;
		
		while(itemIterator.hasNext()) {
			long end222 = System.currentTimeMillis();
			boolean isInsert = false;
			boolean isUpdate = false;
			Item item=(Item)itemIterator.next();
			if(item.getNumIid() == 0L){
				continue;
			}else{
				// 判断商品在中间库里是否忆经存在。
				values=itemDao.findObject("select baihuiid,modified from titem where  num_iid= ?",new Object[]{item.getNumIid()});
//				logger.info("执行select baihuiid,modified from titem where  num_iid= ? 用时" + (sqlend - sqlsta)+ "毫秒");
				if(values!=null && values.size()>0) {
					if(values.get("baihuiid") != null){
						if((item.getModified() != null && values.get("modified") == null) || (values.get("modified") != null && ((Timestamp)values.get("modified")).before(item.getModified()))){
							isUpdate = true;
						}else{
							continue;
						}
					}
				}else {
					isInsert = true;
					insertCount++;
				}
			}
			List paramList=new ArrayList();
			paramList.add(item.getTitle());
			paramList.add(item.getDesc());
			paramList.add(item.getCid()==null?null:item.getCid().longValue());
			long star12 = System.currentTimeMillis();
			paramList.add(getProductCategory(item.getCid()));
//			long end12 = System.currentTimeMillis();
//			log("处理分类用时" + (end12-star12) + "毫秒");
			paramList.add(item.getPrice()==null?null:Float.parseFloat(item.getPrice()));
			if(item.getScore() != null){
				paramList.add(item.getScore().floatValue());
			}else{
				paramList.add(0L);
			}
			paramList.add(item.getCreated());
			paramList.add(item.getModified());
			paramList.add(getSessionInfo().getVisitor_id());
			paramList.add(item.getProps());
//			List numList=new ArrayList();
//			numList.add(item.getNumIid());
//			Sku sku=skuCase.getSkuByNumIds(item.getNumIid());
//			if(sku != null) {
////				Sku sku=skus.get(item.getNumIid());
//				paramList.add(sku.getQuantity());
//				paramList.add("有货");
//			}
//			else {
			paramList.add(item.getNum());
			if(item.getNum()==null || item.getNum()<=0) {
				paramList.add("无货");
			}else{
				paramList.add("有货");
			}
//			}
			paramList.add(item.getListTime());
			paramList.add(item.getOuterId());
			//primary key
			paramList.add(item.getNumIid().toString());
			nIndex++;
			markImportProgress((int)(((float)nIndex)/(itemList.size()+itemList.size()*0.1)*100));
            //停止一分钟后执行,频率不能过高
           // Util.stopOneMinute();
			if(isInsert){
				allInsertTitem.add(paramList.toArray());
			}
			if(isUpdate){
				allUpdateTitem.add(paramList.toArray());
			}
//			long end22 = System.currentTimeMillis();
//			log("处理一条数据用时 " + (end22 - end222) + "豪秒");
			
			numIidsBuffer.append(item.getNumIid());
		
			if(count >= 39){
				insertSku(skuCase, numIidsBuffer.toString());
				count = 0;
				numIidsBuffer = new StringBuffer();
			}else{
				numIidsBuffer.append(",");
				count ++;
			}
		}
		
		if(numIidsBuffer != null && numIidsBuffer.length() > 0 ){
			insertSku(skuCase, numIidsBuffer.substring(0, numIidsBuffer.length() - 1));
		}

		String sql=null;
		if(allInsertTitem != null){
			sql="insert into titem(title,description,cid,seller_cids,price,score,created,modified,userid,props,invnum,storestatus,list_time,outer_id,num_iid) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			itemDao.updateAndInsert(null, sql, allInsertTitem);
//			logger.info("执行插入sql" +allInsertTitem.size() + "条用时" + (end11 - star11) + "毫秒");
		}
		if(allUpdateTitem != null){
			sql="update titem set exported = 2,title=?,description=?,cid=?,seller_cids=?,price=?,score=?,created=?,modified=?,userid=?,props=?,invnum=?,storestatus=?,list_time=? ,outer_id = ? where num_iid=? ";
			itemDao.updateAndInsert(null, sql, allUpdateTitem);
//			logger.info("执行updatesql" + allUpdateTitem.size() +  "条用时" + (end12 - star12) + "毫秒");
		}
		
		long end1 = System.currentTimeMillis();
		logger.info("用户[" + getSessionInfo().getVisitor_id() + "]往中间库里写入" + insertCount + "件商品用时" + (end1 - end) + "毫秒");
		markImportProgress(90);
	}

	private void insertSku(SKUCase skuCase, String numIidsBuffer) throws Exception, NamingException,
			SQLException {
		List<TaobaoObject> sukList = new ArrayList<TaobaoObject>();
		List<Sku> skus=skuCase.getSkuByNumIds(numIidsBuffer.toString());
		if(skus == null){
			return;
		}
		CommonDAO commonDAO = new CommonDAO();
		List<String> skuids = commonDAO.findListString(
				" select skuId from tbsku where userid = ? ",
				new Object[] { getSessionInfo().getVisitor_id() });
		
		for(Sku sku: skus){
			BSku bSku = new BSku();
			if (skuids != null
					&& skuids.contains(String.valueOf(sku.getSkuId()))) {
				continue;
			}
			// 拷贝源对象中的值到目标对象
			Util.copy(bSku, sku);
			bSku.setUserId((long)getSessionInfo().getVisitor_id());
			sukList.add(bSku);
		}
		Connection cn = null;
		cn = DBConnectionMgr.getConnection();
		OrderDAO orderDAO = new OrderDAO();
		if (sukList != null && sukList.size() > 0) {
			orderDAO.insert(sukList, cn);
			sukList.clear();
		}
	}

    private ItemsOnsaleGetResponse  getNextPage(ItemsOnsaleGetRequest req, long page) throws Exception {
        req.setPageNo(page);
        try {
            return getTaoBaoClient().execute(req, getSessionInfo().getTopSession());
        } catch (ApiException e) {
            throw new Exception(e);
        }
    }
    
    private ItemsInventoryGetResponse getInventoryPage(ItemsInventoryGetRequest req, long page) throws Exception {
        req.setPageNo(page);
        try {
            return getTaoBaoClient().execute(req, getSessionInfo().getTopSession());
        } catch (ApiException e) {
            throw new Exception(e);
        }
    }
    
    /*
     *
     */
    public String getProductCategory(long cid) throws Exception {
        ItemcatsGetRequest req=new ItemcatsGetRequest();
        String result="";

        long lngFetchCid=cid;
        while(lngFetchCid>0) {
            req.setFields("cid,parent_cid,name,is_parent");
            req.setCids("" + lngFetchCid);
            ItemcatsGetResponse response = null;
            try {
                response = getTaoBaoClient().execute(req);
                List itemCats=response.getItemCats();
                if(itemCats != null && itemCats.size()>0) {
                    ItemCat itemCat=(ItemCat)itemCats.get(0);
                    if(itemCat==null) {
                        break;
                    }
                    lngFetchCid=itemCat.getParentCid();
                    result = itemCat.getName() + " 》 " + result;
                }
                else {
                    lngFetchCid=0;
                }
            } catch (ApiException e) {
                throw new Exception(e);
            }
        }
        if(result.length()>0) {
            result=result.substring(0,result.length()-1);
        }
        return result;
    }

    /**
     * 标识当前抽取进度
     */
    public void markImportProgress(int progress) {
    	getSessionInfo().setProductImportProgress(progress);
    }

    /**
     * 查看当前抽取进度
     */
    public int viewImportProgress(){
    	return getSessionInfo().getProductImportProgress();
    }

    public List<Item> getProducts(String numids) throws Exception {
        ItemsListGetRequest req=new ItemsListGetRequest();
        req.setFields("num_iid,title,valid_thru,list_time,delist_time");
        req.setNumIids(numids);
        try {
            ItemsListGetResponse response = getTaoBaoClient().execute(req, getSessionInfo().getTopSession());
            return response.getItems();
        } catch (ApiException e) {
            throw new Exception(e);
        }
    }
}

	